package com.elitel.frame.business.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.elitel.frame.base.component.RedisCacheComponent;
import com.elitel.frame.business.service.ExecuteSqlService;
import com.elitel.frame.business.service.SingleReportServerService;
import com.elitel.frame.core.util.JasperHelper;
import com.elitel.frame.main.dao.BaseRepaddonsMapper;
import com.elitel.frame.main.dao.BaseReptemplateMapper;
import com.elitel.frame.main.dao.CfgExtrepMapper;
import com.elitel.frame.main.dao.ext.ExtBaseRepconfigMapper;
import com.elitel.frame.main.entity.BaseRepaddons;
import com.elitel.frame.main.entity.BaseRepconfig;
import com.elitel.frame.main.entity.BaseReptemplate;
import com.elitel.frame.main.entity.CfgDb;
import com.elitel.frame.main.entity.CfgExtrep;
import com.elitel.frame.main.entity.CfgField;
import com.elitel.frame.main.entity.vo.ReportColumn;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

@Service
public class SingleReportServerServiceImpl implements SingleReportServerService{
	
	@Autowired
	private RedisCacheComponent redisCacheComponent;
	@Autowired
	private CfgExtrepMapper cfgExtrepMapper;
	@Autowired
	private ExecuteSqlService executeSqlService;
	@Autowired
	private BaseReptemplateMapper baseReptempletMapper;
	@Autowired
	private  ExtBaseRepconfigMapper extBaseRepconfigMapper;
	@Autowired
	private BaseRepaddonsMapper baseRepaddonsMapper;
	
	@Override
	public void singleReportToHtml(String guid, String pageIndex, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> map = loadReportTemplateInformation(guid, request, response);
		String exportFilePath = map.get("exportFilePath").toString();
		File reportFile = (File) map.get("reportFile");
		HttpServletRequest rerequest = (HttpServletRequest) map.get("request");
		HttpServletResponse reresponse = (HttpServletResponse) map.get("response");
		Map parameters = (Map) map.get("parameters");
		JRDataSource datasource = (JRDataSource) map.get("datasource");
	      try {
			JasperHelper.showHtml(exportFilePath , reportFile.getPath(), rerequest,
					reresponse, parameters, datasource, Integer.valueOf(pageIndex));
		} catch (JRException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public Integer singleReportTotalPage(String guid, HttpServletRequest request, HttpServletResponse response) {
		Integer returnPage = null;
		Map<String, Object> map = loadReportTemplateInformation(guid, request, response);
		String exportFilePath = map.get("exportFilePath").toString();
		File reportFile = (File) map.get("reportFile");
		HttpServletRequest rerequest = (HttpServletRequest) map.get("request");
		HttpServletResponse reresponse = (HttpServletResponse) map.get("response");
		Map parameters = (Map) map.get("parameters");
		JRDataSource datasource = (JRDataSource) map.get("datasource");
	    try {
			returnPage = JasperHelper.returnPage(reportFile.getPath(), parameters, datasource);
		} catch (JRException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		  
	     return returnPage;
	}

	@Override
	public void singleReportToPdf(String guid, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = loadReportTemplateInformation(guid, request, response);
		String exportFilePath = map.get("exportFilePath").toString();
		File reportFile = (File) map.get("reportFile");
		HttpServletRequest rerequest = (HttpServletRequest) map.get("request");
		HttpServletResponse reresponse = (HttpServletResponse) map.get("response");
		Map parameters = (Map) map.get("parameters");
		JRDataSource datasource = (JRDataSource) map.get("datasource");
	      try {
			JasperHelper.showPdf(exportFilePath , reportFile.getPath(), rerequest,
					reresponse, parameters, datasource);
		} catch (JRException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}


	@Override
	public void singleReportExportPdf(String guid, String pageIndex, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> map = loadReportTemplateInformation(guid, request, response);
		String exportFilePath = map.get("exportFilePath").toString();
		File reportFile = (File) map.get("reportFile");
		HttpServletRequest rerequest = (HttpServletRequest) map.get("request");
		HttpServletResponse reresponse = (HttpServletResponse) map.get("response");
		Map parameters = (Map) map.get("parameters");
		JRDataSource datasource = (JRDataSource) map.get("datasource");
		
		JasperHelper.export("pdf", exportFilePath, reportFile, request,
                    response, parameters, datasource);
		
	}
	/**
	   * 
	   * @Title: loadReportTemplateInformation 
	   * @Description: TODO(加载报表信息) 
	   * @author Fanwenquan
	   * @return Map<String,Object>
	   * @throws
	   */
	  private Map<String, Object> loadReportTemplateInformation(String guid, HttpServletRequest request,
	            HttpServletResponse response) {
		  //返回值
		  Map<String, Object> returnMap = new HashMap<String, Object>();
		  //报表参数
		  Map parameters = new HashMap();
		  //跟据参数查出报表服务的数据源和字段存储关键字
		  CfgExtrep cfgExtrep = cfgExtrepMapper.selectByPrimaryKey(guid);
		  BaseReptemplate baseReptemplet = null;
		  List<BaseRepconfig> repConfig = null;
		  List<ReportColumn> columnList = new ArrayList<ReportColumn>();
		  //获取数据源  表字段信息
		  Map<String, Object> map = loadDbInformation(cfgExtrep);
		  CfgDb prop = (CfgDb) map.get("datasource");
		  List<CfgField> cfgList = (List<CfgField>) map.get("tableMessage");
		  String str = "select * from " + cfgList.get(0).getDtName();
		  List<Map<String, Object>> list = executeSqlService.executeSql(prop, str);
		  if(null != cfgExtrep) {
			  //查询模板信息
			   baseReptemplet = baseReptempletMapper.selectByPrimaryKey(cfgExtrep.getTempid());
			  //查询填报信息
			   repConfig = extBaseRepconfigMapper.selectRepConfigByRguid(cfgExtrep.getGuid());
			 String columnArray[] = cfgExtrep.getFields().split(",");
			 if(columnArray.length >= 1) {
				 for (CfgField cfg : cfgList) {
					if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[0])) {
						parameters.put("COLUMNTITLE1", cfg.getDfNameCn());
						break;
					}
				}
			 }
			 if(columnArray.length >= 2) {
				 for (CfgField cfg : cfgList) {
					if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[1])) {
						parameters.put("COLUMNTITLE2", cfg.getDfNameCn());
						break;
					}
				}
			 }
			 if(columnArray.length >= 3) {
				 for (CfgField cfg : cfgList) {
					if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[2])) {
						parameters.put("COLUMNTITLE3", cfg.getDfNameCn());
						break;
					}
				}
			 }
			 if(columnArray.length >= 4) {
				 for (CfgField cfg : cfgList) {
					if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[3])) {
						parameters.put("COLUMNTITLE4", cfg.getDfNameCn());
						break;
					}
				}
			 }
			 if(columnArray.length >= 5) {
				 for (CfgField cfg : cfgList) {
					if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[4])) {
						parameters.put("COLUMNTITLE5", cfg.getDfNameCn());
						break;
					}
				}
			 }
			 if(columnArray.length >= 6) {
				 for (CfgField cfg : cfgList) {
					if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[5])) {
						parameters.put("COLUMNTITLE6", cfg.getDfNameCn());
						break;
					}
				}
			 }
			 if(columnArray.length >= 7) {
				 for (CfgField cfg : cfgList) {
					if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[6])) {
						parameters.put("COLUMNTITLE7", cfg.getDfNameCn());
						break;
					}
				}
			 }
			 if(columnArray.length >= 8) {
				 for (CfgField cfg : cfgList) {
					if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[7])) {
						parameters.put("COLUMNTITLE8", cfg.getDfNameCn());
						break;
					}
				}
			 }
			 if(columnArray.length >= 9) {
				 for (CfgField cfg : cfgList) {
					if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[8])) {
						parameters.put("COLUMNTITLE9", cfg.getDfNameCn());
						break;
					}
				}
			 }
			 if(columnArray.length >= 10) {
				 for (CfgField cfg : cfgList) {
					if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[9])) {
						parameters.put("COLUMNTITLE10", cfg.getDfNameCn());
						break;
					}
				}
			 }
			 if(columnArray.length >= 11) {
				 for (CfgField cfg : cfgList) {
					if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[10])) {
						parameters.put("COLUMNTITLE11", cfg.getDfNameCn());
						break;
					}
				}
			 }
			 if(columnArray.length >= 12) {
				 for (CfgField cfg : cfgList) {
					if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[11])) {
						parameters.put("COLUMNTITLE12", cfg.getDfNameCn());
						break;
					}
				}
			 }
			 for (Map<String, Object> m : list) {
					ReportColumn repColumn= new ReportColumn();
						if(0 < columnArray.length) {
							repColumn.setColunmValue1(m.get(columnArray[0]).toString());
						}
						if(1 < columnArray.length) {
							repColumn.setColunmValue2(m.get(columnArray[1]).toString());
						}
						if(2 < columnArray.length) {
							repColumn.setColunmValue3(m.get(columnArray[2]).toString());
						}
						if(3 < columnArray.length) {
							repColumn.setColunmValue4(m.get(columnArray[3]).toString());
						}
						if(4 < columnArray.length) {
							repColumn.setColunmValue5(m.get(columnArray[4]).toString());
						}
						if(5 < columnArray.length) {
							repColumn.setColunmValue6(m.get(columnArray[5]).toString());
						}
						if(6 < columnArray.length) {
							repColumn.setColunmValue7(m.get(columnArray[6]).toString());
						}
						if(7 < columnArray.length) {
							repColumn.setColunmValue7(m.get(columnArray[7]).toString());
						}
						if(8 < columnArray.length) {
							repColumn.setColunmValue9(m.get(columnArray[8]).toString());
						}
						if(9 < columnArray.length) {
							repColumn.setColunmValue10(m.get(columnArray[9]).toString());
						}
						if(10 < columnArray.length) {
							repColumn.setColunmValue11(m.get(columnArray[10]).toString());
						}
						if(11 < columnArray.length) {
							repColumn.setColunmValue12(m.get(columnArray[11]).toString());
						}
						columnList.add(repColumn);
				}
			 parameters.put("RTITLE", cfgExtrep.getRtitle());
		  }
		  // 报表数据源  
     //STEP 2 : 指定数据源
		 JRDataSource datasource = new JRBeanCollectionDataSource(columnList);
		 //STEP 3 : 指定模板文件
		 ServletContext context = request.getSession().getServletContext();
		 File reportFile = null;
		 reportFile = new File(context.getRealPath(baseReptemplet.getTemplateUrl()));
		 String exportFilePath = UUID.randomUUID().toString();
	      //exporterParameters.put(JRHtmlExporterParameter.IS_WRAP_BREAK_WORD , true);
	      SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
	      SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
	      for (BaseRepconfig m : repConfig) {
		    	 if(null != m.getRaguid() && !"".equals(m.getRaguid())) {
		    		 BaseRepaddons	br = baseRepaddonsMapper.selectByPrimaryKey(m.getRaguid());
		    		 if(br.getPropname().equals("DATE")){
		 				if(m.getPropvalue().equals("@DATE")){
		 					parameters.put(br.getPropname(), sdf.format(new Date()));
		 				} else if(m.getPropvalue().equals("@TIME")) {
		 					parameters.put(br.getPropname(), sd.format(new Date()));
		 				}
		 				continue;
		 			}
		    		 parameters.put(br.getPropname(), m.getPropvalue());
		    	 }
				
			}
	      returnMap.put("parameters", parameters);
	      returnMap.put("exportFilePath", exportFilePath);
	      returnMap.put("request", request);
	      returnMap.put("response", response);
	      returnMap.put("reportFile", reportFile);
	      returnMap.put("datasource", datasource);
	    return returnMap;
	  }
	  
	  /**
	   * 
	   * @Title: loadDbInformation 
	   * @Description: TODO(加载数据源等基本信息) 
	   * @author Fanwenquan
	   * @return Map<String,Object>
	   * @throws
	   */
	  private Map<String, Object> loadDbInformation(CfgExtrep cfgExtrep){
		    Map<String, Object> map = new HashMap<String, Object>();
			if(null != cfgExtrep) {
				//查询表名,表字段信息
				List<CfgField> cfgList = redisCacheComponent.cfgFieldRedisCache(cfgExtrep.getDtConfigId());
			    //查询及数据源标识
			    CfgDb prop = redisCacheComponent.cfgDBRedisCache(cfgExtrep.getDtDbKey());
				map.put("tableMessage", cfgList);
				map.put("datasource", prop);
			}
		  return map;
	  }

}
